﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using OS.Common.Core;
using OS.Common.Enums;
using OS.Common.Plugs.LogPlug;
using OS.Http.Models;

namespace OS.Http.Extention
{
    /// <summary>
    /// 通用请求结果扩展
    /// </summary>
    public static class BaseRestExtention
    {
        /// <summary>
        /// 处理远程请求方法，并返回需要的实体
        /// </summary>
        /// <typeparam name="T">需要返回的实体类型</typeparam>
        /// <param name="request">远程请求组件的request基本信息</param>
        /// <param name="formatFunc">处理内容委托</param>
        /// <param name="client">自定义httpclient</param>
        /// <param name="moduleName">模块名称</param>
        /// <returns></returns>
        public static async Task<T> RestCommon<T>(this BaseHttpRequest request,
            Func<HttpResponseMessage, Task<T>> formatFunc, HttpClient client = null, string moduleName = "default")
            where T : CustomResult, new()
        {
            T val;
            try
            {
                val = await formatFunc(await request.RestSend(client));
            }
            catch (Exception exception)
            {
                var val2 = new T
                {
                    Code = (int)ResultType.InnerError,
                    Message = exception.Message
                };
                val = val2;
                LogUtil.Error($"基类请求出错，错误信息：{exception.Message}，RestCommon，{moduleName}");
            }

            object val3 = val ?? new T
            {
                Code = (int)ResultType.None,
                Message = "未发现结果"
            };

            return (T) val3;
        }

        /// <summary>
        /// 使用Json格式化内容方法
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="response">响应结果</param>
        /// <returns></returns>
        private static async Task<T> JsonFormat<T>(HttpResponseMessage response) where T : CustomResult, new()
        {
            if (response.IsSuccessStatusCode)
                return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
            var val = new T
            {
                Code = (int)(0 - response.StatusCode),
                Message = response.ReasonPhrase
            };
            return val;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="client"></param>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public static async Task<T> RestCommonJson<T>(this BaseHttpRequest request, HttpClient client = null,
            string moduleName = "default") where T : CustomResult, new()
        {
            return await RestCommon(request, JsonFormat<T>, client, moduleName);
        }
    }
}